package admin

import (
	"anban/logic"
	"anban/models"
	"anban/service"
	"anban/utils"
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/astaxie/beego"
	"html/template"
	"os"
	"strconv"
	"time"
)

type StudentController struct {
	BaseController
}

func (c *StudentController) Add() {
	userAdminId := c.GetSession("userAdminId")
	p := map[string]interface{}{}
	p["id"] = userAdminId
	p["relation"] = true
	userAdmin := service.GetUserAdminInfo(p)

	if userAdmin.UserAdminRole.School.Id > 0 {
		p = map[string]interface{}{}
		p["schoolId"] = userAdmin.UserAdminRole.School.Id
		_, c.Data["classList"] = service.GetClassList(p)
	}

	p = map[string]interface{}{}
	_, c.Data["schoolList"] = service.GetSchoolList(p)

	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "admin/student/add.html"
}

func (c *StudentController) DoAdd() {
	var res *utils.ResJsonStruct
	input := c.Input()

	err := logic.AddStudent(input)
	if err != nil {
		res = utils.ResJson(err.Code(), err.Error(), "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res = utils.ResJson(1, "添加成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}

func (c *StudentController) ExcelAdd() {
	userAdminId := c.GetSession("userAdminId")
	p := map[string]interface{}{}
	p["id"] = userAdminId
	p["relation"] = true
	userAdmin := service.GetUserAdminInfo(p)

	if userAdmin.UserAdminRole.School.Id > 0 {
		p = map[string]interface{}{}
		p["schoolId"] = userAdmin.UserAdminRole.School.Id
		_, c.Data["classList"] = service.GetClassList(p)
	}

	p = map[string]interface{}{}
	_, c.Data["schoolList"] = service.GetSchoolList(p)

	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "admin/student/excel_add.html"
}

func (c *StudentController) DoExcelAdd() {
	var res *utils.ResJsonStruct
	input := c.Input()

	err := logic.AddStudentFromExcel(input)
	if err != nil {
		res = utils.ResJson(err.Code(), err.Error(), "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res = utils.ResJson(1, "导入成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}

func (c *StudentController) Edit() {
	id := c.Ctx.Input.Param(":id")

	p := map[string]interface{}{}
	p["relation"] = true
	p["convert"] = true
	p["id"] = id
	record := service.GetStudentInfo(p)
	c.Data["record"] = record

	p = map[string]interface{}{}
	_, c.Data["schoolList"] = service.GetSchoolList(p)

	p = map[string]interface{}{}
	p["schoolId"] = record.School.Id
	_, c.Data["classList"] = service.GetClassList(p)

	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "admin/student/edit.html"
}

func (c *StudentController) DoEdit() {
	var res *utils.ResJsonStruct
	input := c.Input()

	err := logic.EditStudent(input)
	if err != nil {
		res = utils.ResJson(err.Code(), err.Error(), "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	res = utils.ResJson(1, "修改成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}

func (c *StudentController) ShowList() {
	curPage, _ := strconv.Atoi(c.GetString("p"))
	if curPage <= 0 {
		curPage = 1
	}
	perCount, _ := beego.AppConfig.Int("percount")
	symPageCount, _ := beego.AppConfig.Int("symmetricpagecount")

	userAdminId := c.GetSession("userAdminId")
	p := map[string]interface{}{}
	p["id"] = userAdminId
	p["relation"] = true
	userAdmin := service.GetUserAdminInfo(p)

	p = map[string]interface{}{}
	schoolId := c.GetString("school_id")
	if userAdmin.UserAdminRole.School.Id > 0 {
		schoolId = fmt.Sprintf("%d", userAdmin.UserAdminRole.School.Id)
	}
	if len(schoolId) > 0 {
		p["schoolId"] = schoolId
		c.Data["schoolId"] = utils.Atoi64(schoolId)
	} else {
		c.Data["schoolId"] = -1
	}
	classId := c.GetString("class_id")
	if len(classId) > 0 {
		p["classId"] = classId
		c.Data["classId"] = utils.Atoi64(classId)
	} else {
		c.Data["classId"] = -1
	}
	sn := c.GetString("sn")
	c.Data["sn"] = sn
	if len(sn) > 0 {
		p["sn"] = sn
	}
	realName := c.GetString("real_name")
	c.Data["realName"] = realName
	if len(realName) > 0 {
		p["realName"] = realName
	}
	idCard := c.GetString("id_card")
	c.Data["idCard"] = idCard
	if len(idCard) > 0 {
		p["idCard"] = idCard
	}
	exportExcel := c.GetString("export_excel")
	if len(exportExcel) <= 0 {
		p["curPage"] = curPage
		p["perCount"] = perCount
	}
	p["relation"] = true
	p["convert"] = true
	totalCount, recordList := service.GetStudentList(p)
	if len(exportExcel) > 0 && totalCount > 0 {
		c.ExportExcel(recordList)
		return
	}
	paginator := utils.NewPaginator(int(totalCount), perCount, symPageCount, curPage)
	c.Data["paginator"] = paginator.GetPageHtml()
	c.Data["recordList"] = recordList

	p = map[string]interface{}{}
	_, c.Data["schoolList"] = service.GetSchoolList(p)
	if len(schoolId) > 0 {
		p = map[string]interface{}{}
		p["schoolId"] = schoolId
		_, c.Data["classList"] = service.GetClassList(p)
	}

	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "admin/student/list.html"
}

func (c *StudentController) ExportExcel(recordList []*models.Student) {
	f := excelize.NewFile()
	sheetName := "sheet1"
	index := f.NewSheet(sheetName)
	col := 65
	header := []string{"唯一标识", "姓名", "身份证号", "就读学校", "班级", "状态", "注册时间"}
	for _, h := range header {
		f.SetCellValue(sheetName, string(col) + "1", h)
		col++
	}
	row := 2
	style, _ := f.NewStyle(`{"alignment":{"horizontal":"center"}}`)
	f.SetColWidth(sheetName, "A", "G", 25)
	f.SetCellStyle(sheetName, "A1", fmt.Sprintf("G%d", len(recordList) + 1), style)
	for _, record := range recordList {
		f.SetCellValue(sheetName, fmt.Sprintf("A%d", row), record.Sn)
		f.SetCellValue(sheetName, fmt.Sprintf("B%d", row), record.RealName)
		f.SetCellValue(sheetName, fmt.Sprintf("C%d", row), record.IdCard)
		f.SetCellValue(sheetName, fmt.Sprintf("D%d", row), record.School.Name)
		f.SetCellValue(sheetName, fmt.Sprintf("E%d", row), record.Class.Name)
		f.SetCellValue(sheetName, fmt.Sprintf("F%d", row), record.StatusShow)
		f.SetCellValue(sheetName, fmt.Sprintf("G%d", row), record.CreatedShow)
		row++
	}
	f.SetActiveSheet(index)
	d := "./static/export/" + time.Now().Format("20060102") + "/"
	if _, err := os.Stat(d); err != nil {
		os.MkdirAll(d, os.ModePerm)
	}
	saveName := d + "学生_" + time.Now().Format("20060102150405") + ".xlsx"
	err := f.SaveAs(saveName)
	if err != nil {
		c.Ctx.WriteString("导出失败")
		return
	}
	c.Ctx.Output.Download(saveName)
}

// 学生家长列表
func (c *StudentController) ParentList() {
	id := c.Ctx.Input.Param(":id")

	p := map[string]interface{}{}
	p["id"] = id
	student := service.GetStudentInfo(p)

	var parentList []*models.User
	if len(student.FamilySn) > 0 {
		p = map[string]interface{}{}
		p["relation"] = true
		p["studentId"] = student.Id
		p["familySn"] = student.FamilySn
		_, parentList = service.GetUserList(p)
	}

	c.Data["parentList"] = parentList
	c.TplName = "admin/student/parent_list.html"
}